package dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import trip.HibernateUtil;
import trip.Person;
import trip.Person_trip;
import trip.Stop;
import trip.Trip;

public class Person_tripDAOImpl extends GenericDaoImpl<Person_trip> implements Person_tripDAO {
	public Person_tripDAOImpl(Class<Person_trip> type) {
		super(type);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person_trip> getByPerson(Person person) {
		Session session = null;
		List<Person_trip> result = new ArrayList<Person_trip>();
		if (person == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select pt from Person_trip pt "
					+ "where pt.person = :id");
			query.setLong("id", person.getId());
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person_trip> getByTrip(Trip trip) {
		Session session = null;
		List<Person_trip> result = new ArrayList<Person_trip>();
		if (trip == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select pt from Person_trip pt "
					+ "where pt.trip = :id");
			query.setLong("id", trip.getId());
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Person_trip> getByStops(Stop departure, Stop arrival) {
		Session session = null;
		List<Person_trip> result = new ArrayList<Person_trip>();
		if (departure == null || arrival == null)
			return result;
		try {
			session = HibernateUtil.getFactory().openSession();
			session.beginTransaction();
			Query query = session.createQuery("select pt from Person_trip pt "
					+ "where pt.departure_stop = :did and pt.arrival_stop = :aid");
			query.setLong("did", departure.getId());
			query.setLong("aid", arrival.getId());
			result = query.list();
			session.getTransaction().commit();
			return result;
		} finally {
			if (session != null && session.isOpen())
				session.close();
		}
	}
}
